/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package pl.lodz.p.ftims.ProjektZespolowy2.endpoint;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Stateful;

import pl.lodz.p.ftims.ProjektZespolowy2.entities.Role;
import pl.lodz.p.ftims.ProjektZespolowy2.entities.User;
import pl.lodz.p.ftims.ProjektZespolowy2.facades.RolesFacadeLocal;
import pl.lodz.p.ftims.ProjektZespolowy2.facades.UsersFacadeLocal;

/**
 *
 * @author Łukasz Gadomski
 */
@Stateful
public class Endpoint implements EndpointLocal {

    @EJB
    private UsersFacadeLocal usersFacade;
	@EJB
	private RolesFacadeLocal rolesFacade;
	
    @Override
    public User getUserByPesel(Integer pesel) {
    	return usersFacade.findByPesel(pesel);
    }

	@Override
	public List<Role> getRolesList() {
		return rolesFacade.findAll();
	}

	@Override
	public String registerNewUser(User newUser) {
		try {
			newUser.setPassword(getMD5(newUser.getPassword()));
			usersFacade.create(newUser);
			return "registrationSuccess";
		} catch (Exception e) {
			return "registrationFailure";
		}
	}
	
	@Override
	public boolean checkPasswordForUser(Integer pesel, String password) {
		String encryptedPassword = getMD5(password);
		if (usersFacade.findByPesel(pesel).getPassword().equals(encryptedPassword)) {
			return true;
		} else {
			return false;
		}
	}
	
	private String getMD5(String text) {
        MessageDigest m = null;
        try {
            m = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException ex) {
        	ex.printStackTrace();
        }
        m.update(text.getBytes(), 0, text.length());
        String digest = new BigInteger(1, m.digest()).toString(16);
        return digest;
    }
    
}
